package com.hippo.core.ui.components

import android.R.attr.text
import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 倒计按钮（单位秒）
 */
@Composable
fun TimerButton(
    text: String,
    duration: Int,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    onEnd: (() -> Unit)? = null,
) {
    var count by remember { mutableIntStateOf(duration) }


    LaunchedEffect(Unit) {
        while (count > 0) {
            delay(1000)
            count--
        }
        onEnd?.invoke()
    }

    OutlinedButton(
        modifier = modifier,
        onClick = onClick,
        enabled = count <= 0,
        border = BorderStroke(
            1.dp,
            if (count > 0) Color.LightGray else MaterialTheme.colorScheme.primary
        ),
    ) {

        val msg = if (count > 0) {
            "$text ( $count s )"
        } else {
            text
        }

        Text(
            text = msg,
            textAlign = TextAlign.Center,
            color = if (count > 0) Color.LightGray else MaterialTheme.colorScheme.primary,
            modifier = modifier
                .fillMaxWidth()
                .padding(4.dp),
        )
    }


}